package com.xpec.c4.service.utility;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;

import net.sf.cindy.Buffer;
import net.sf.cindy.buffer.BufferFactory;

/**
 * 使用java.util.zip的自带压缩
 * 
 * @author Bany
 *
 * @since 2009-1-2 下午05:29:51
 *
 */

public class JavaZipDeflater {

	private Deflater compresser = new Deflater();
	
	public Buffer compress(Buffer buffer){
		byte[] input=new byte[buffer.remaining()];
		buffer.get(input);
		byte[] output=compressBytes(input);
		Buffer outBuffer=BufferFactory.allocate(output.length);
		outBuffer.put(output);
		return outBuffer.flip();
	}

	public byte[] compressBytes(byte input[]) {
		compresser.reset();
		compresser.setInput(input);
		compresser.finish();
		byte output[] = new byte[0];
		ByteArrayOutputStream o = new ByteArrayOutputStream(input.length);
		try {
			byte[] buf = new byte[input.length];
			int got;
			while (!compresser.finished()) {
				got = compresser.deflate(buf);
				o.write(buf, 0, got);
			}
			output = o.toByteArray();
		} finally {
			try {
				o.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return output;
	}


}
